using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_Model.WorkOrderTask
{
    /// <summary>
    /// 工单任务服务 - 提供工单任务的数据操作
    /// </summary>
    public class WorkOrderTaskService
    {
        private readonly WorkOrderTaskApiService _apiService;
        private List<WorkOrderTaskModel> _cachedTasks;

        public WorkOrderTaskService()
        {
            _apiService = new WorkOrderTaskApiService();
            _cachedTasks = new List<WorkOrderTaskModel>();
        }

        #region API数据操作

        /// <summary>
        /// 获取工单任务数据（从API）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">页大小</param>
        /// <returns></returns>
        public async Task<(List<WorkOrderTaskModel> tasks, int totalCount)> GetWorkOrderTasksAsync(int pageIndex = 1, int pageSize = 10)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 开始调用API获取数据，页码={pageIndex}, 页大小={pageSize}");
                var response = await _apiService.GetWorkOrderTaskPageAsync(pageIndex, pageSize);
                System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: API调用完成，IsSuc={response?.IsSuc}, Data是否为null={response?.Data == null}");

                if (response.IsSuc && response.Data != null)
                {
                    System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: API返回数据项数={response.Data.Data?.Count ?? 0}, 总数={response.Data.TotalCount}");

                    var tasks = new List<WorkOrderTaskModel>();
                    for (int i = 0; i < response.Data.Data.Count; i++)
                    {
                        var apiModel = response.Data.Data[i];
                        var uiModel = _apiService.ConvertToUIModel(apiModel, (pageIndex - 1) * pageSize + i + 1);
                        tasks.Add(uiModel);
                        System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 转换任务 {i + 1}: {uiModel.TaskNumber} - {uiModel.TaskName}");
                    }

                    // 更新缓存
                    _cachedTasks = tasks;

                    System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: 数据转换完成，返回{tasks.Count}个任务");
                    return (tasks, response.Data.TotalCount);
                }
                else
                {
                    // API调用失败，返回空数据
                    System.Diagnostics.Debug.WriteLine($"WorkOrderTaskService: API调用失败，返回空数据。错误信息: {response?.Msg}");
                    return (new List<WorkOrderTaskModel>(), 0);
                }
            }
            catch (Exception ex)
            {
                // 异常处理，返回空数据
                System.Diagnostics.Debug.WriteLine($"获取工单任务数据失败: {ex.Message}");
                return (new List<WorkOrderTaskModel>(), 0);
            }
        }

        /// <summary>
        /// 获取模拟的工单任务数据（保留作为备用）
        /// </summary>
        /// <returns></returns>
        public async Task<List<WorkOrderTaskModel>> GetMockWorkOrderTasksAsync()
        {
            // 模拟异步操作
            await Task.Delay(100);

            var tasks = new List<WorkOrderTaskModel>();
            var random = new Random();
            var statuses = new[] { "未派工", "已下达", "进行中", "已完成", "已暂停" };
            var taskNames = new[] { "生产工件任务1", "生产工件任务2", "生产工件任务3", "装配任务", "检测任务", "包装任务" };
            var stations = new[] { "站点一", "站点二", "站点三", "站点四", "站点五" };

            for (int i = 1; i <= 50; i++)
            {
                var planStartTime = DateTime.Now.AddDays(-random.Next(0, 30)).AddHours(random.Next(8, 18));
                var actualStartTime = planStartTime.AddMinutes(random.Next(-30, 60));
                var planDurationHours = random.Next(1, 8);
                var actualDurationHours = planDurationHours + random.Next(-1, 3);

                tasks.Add(new WorkOrderTaskModel
                {
                    Id = Guid.NewGuid().ToString(),
                    Index = i,
                    TaskNumber = $"RWBH{i:D4}",
                    TaskName = taskNames[random.Next(taskNames.Length)],
                    StationName = stations[random.Next(stations.Length)],
                    PlanStartTime = planStartTime,
                    ActualStartTime = actualStartTime,
                    PlanDuration = $"{planDurationHours}小时",
                    ActualEndTime = actualStartTime.AddHours(actualDurationHours),
                    ActualDuration = $"{actualDurationHours}小时{random.Next(0, 60)}分钟",
                    Status = statuses[random.Next(statuses.Length)]
                });
            }

            return tasks;
        }

        /// <summary>
        /// 根据条件搜索工单任务
        /// </summary>
        /// <param name="searchText">搜索文本</param>
        /// <param name="status">状态筛选</param>
        /// <param name="station">站点筛选</param>
        /// <param name="startDate">开始日期</param>
        /// <param name="endDate">结束日期</param>
        /// <returns></returns>
        public async Task<List<WorkOrderTaskModel>> SearchWorkOrderTasksAsync(
            string searchText = null,
            string status = null,
            string station = null,
            DateTime? startDate = null,
            DateTime? endDate = null)
        {
            var (allTasks, totalCount) = await GetWorkOrderTasksAsync();

            var filteredTasks = allTasks.AsQueryable();

            // 文本搜索
            if (!string.IsNullOrWhiteSpace(searchText))
            {
                filteredTasks = filteredTasks.Where(t =>
                    (t.TaskNumber != null && t.TaskNumber.Contains(searchText, StringComparison.OrdinalIgnoreCase)) ||
                    (t.TaskName != null && t.TaskName.Contains(searchText, StringComparison.OrdinalIgnoreCase)) ||
                    (t.StationName != null && t.StationName.Contains(searchText, StringComparison.OrdinalIgnoreCase)));
            }

            // 状态筛选
            if (!string.IsNullOrWhiteSpace(status) && status != "全部")
            {
                filteredTasks = filteredTasks.Where(t => t.Status == status);
            }

            // 站点筛选
            if (!string.IsNullOrWhiteSpace(station) && station != "全部")
            {
                filteredTasks = filteredTasks.Where(t => t.StationName == station);
            }

            // 日期筛选
            if (startDate.HasValue)
            {
                filteredTasks = filteredTasks.Where(t => t.PlanStartTime >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                filteredTasks = filteredTasks.Where(t => t.PlanStartTime <= endDate.Value);
            }

            return filteredTasks.ToList();
        }

        /// <summary>
        /// 更新任务状态
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <param name="newStatus">新状态</param>
        /// <returns></returns>
        public async Task<bool> UpdateTaskStatusAsync(string taskId, string newStatus)
        {
            // 模拟异步操作
            await Task.Delay(50);

            // 这里应该是实际的数据库更新操作
            // 目前只是模拟返回成功
            return true;
        }

        /// <summary>
        /// 开工任务
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns></returns>
        public async Task<bool> StartTaskAsync(string taskId)
        {
            return await UpdateTaskStatusAsync(taskId, "进行中");
        }

        /// <summary>
        /// 完工任务
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns></returns>
        public async Task<bool> CompleteTaskAsync(string taskId)
        {
            return await UpdateTaskStatusAsync(taskId, "已完成");
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        /// <param name="taskId">任务ID</param>
        /// <returns></returns>
        public async Task<bool> PauseTaskAsync(string taskId)
        {
            return await UpdateTaskStatusAsync(taskId, "已暂停");
        }

        /// <summary>
        /// 获取所有状态选项
        /// </summary>
        /// <returns></returns>
        public List<string> GetStatusOptions()
        {
            return new List<string> { "全部", "未派工", "已下达", "进行中", "已完成", "已暂停", "已关闭" };
        }

        /// <summary>
        /// 获取所有站点选项
        /// </summary>
        /// <returns></returns>
        public List<string> GetStationOptions()
        {
            return new List<string> { "全部", "站点一", "站点二", "站点三", "站点四", "站点五" };
        }

        /// <summary>
        /// 单个报工
        /// </summary>
        /// <param name="task">工单任务</param>
        /// <param name="reportData">报工数据</param>
        /// <returns></returns>
        public async Task<bool> SubmitWorkReportAsync(WorkOrderTaskModel task, WorkReportRequest reportData)
        {
            try
            {
                var response = await _apiService.SubmitWorkReportAsync(reportData);
                return response.IsSuc;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"报工失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 批量报工
        /// </summary>
        /// <param name="reportDataList">批量报工数据</param>
        /// <returns></returns>
        public async Task<bool> SubmitBatchWorkReportAsync(List<WorkReportRequest> reportDataList)
        {
            try
            {
                var response = await _apiService.SubmitBatchWorkReportAsync(reportDataList);
                return response.IsSuc;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"批量报工失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 创建报工请求数据
        /// </summary>
        /// <param name="task">工单任务</param>
        /// <param name="reportQuantity">报告数量</param>
        /// <param name="testQuantity">测试数量</param>
        /// <param name="qualifiedQuantity">合格数量</param>
        /// <param name="unqualifiedQuantity">不合格数量</param>
        /// <param name="overallResult">总体结果</param>
        /// <param name="remark">备注</param>
        /// <returns></returns>
        public WorkReportRequest CreateWorkReportRequest(
            WorkOrderTaskModel task,
            int reportQuantity,
            int testQuantity,
            int qualifiedQuantity,
            int unqualifiedQuantity,
            string overallResult,
            string remark = "")
        {
            return new WorkReportRequest
            {
                WorkOrderTaskId = task.Id,
                InspectionCode = "INS001", // 默认检验代码
                InspectionName = task.TaskName,
                InspectionType = "质量检验", // 默认值，可根据需要调整
                ProductId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认产品ID
                ProcessStepId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认工艺步骤ID
                StationId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认站点ID
                TeamId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认班组ID
                ReporterId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认报告人ID
                InspectorId = "3fa85f64-5717-4562-b3fc-2c963f66afa6", // 默认检验员ID
                ReportedQuantity = reportQuantity,
                ReportTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                InspectionTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
                InspectionDepartment = "质量部", // 默认值，可根据需要调整
                TestedQuantity = testQuantity,
                QualifiedQuantity = qualifiedQuantity,
                UnqualifiedQuantity = unqualifiedQuantity,
                OverallResult = overallResult,
                Remark = remark
            };
        }

        #endregion
    }
}
